package cn.xorange.commons.core.basic.bean;

import cn.xorange.commons.utils.exception.BaseException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : yangjian
 */
@Getter
public class ResultBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private final int code;
    private final int status;
    private final String msg;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Serializable data;
    @JsonIgnore
    @JSONField(serialize = false)
    private transient HashMap<String, Object> resultMap = new HashMap<>();
    @JsonIgnore
    @JSONField(serialize = false)
    private List<LogApi> logList;

    public void setLogList(List<LogApi> logList){
        this.logList = logList;
    }


    public ResultBean(SystemCode systemCode,Serializable data){
        this.code  = systemCode.getCode();
        this.status = systemCode.getStatus();
        this.msg = systemCode.getMsg();
        this.data = data;

    }

    public static ResultBean onSuccess(){
        return new ResultBean(SystemCode.SUCCESS,null);
    }
    public static ResultBean onSuccess(Object data){
        return new ResultBean(SystemCode.SUCCESS,(Serializable) data);
    }

    public ResultBean put(String key, Object val){
        this.getResultMap().put(key, val);
        if(Objects.isNull(this.data)){
            this.resultMap.put(key, val);
        }else {
            if(this.data instanceof HashMap){
                this.resultMap.put(key,val);
            }else {
                String str = JSON.toJSONString(this.data);
                HashMap<String,Object> map = JSONObject.parseObject(str);
                map.put(key, val);
                this.resultMap = map;
            }
        }
        this.data = resultMap;
        return this;
    }

    public static ResultBean onFail(){
        return new ResultBean(SystemCode.FAIL,null);
    }

    public static ResultBean onFail(String msg){
        SystemCode fail = SystemCode.FAIL;
        fail.setMsg(msg);
        return new ResultBean(fail,null);
    }

    public static ResultBean onFail(BaseException baseException){
        SystemCode sysCode = SystemCode.SYSTEM_EXCEPTION;
        sysCode.setStatus(baseException.getStatus());
        sysCode.setCode(baseException.getCode());
        sysCode.setMsg(baseException.getMessage());
        return new ResultBean(sysCode,null);
    }

    public static ResultBean onFail(SystemCode sysCode){
        return new ResultBean(sysCode,null);
    }
}
